﻿using RuoVea.ExEnum;
using RuoVea.ExSugar.Dto;

namespace RuoVea.Notes.Web.Controllers;

/// <summary>
/// 笔记管理
/// </summary>
[Authorize(Roles = "None")]
public class NoteController : Controller
{
    private readonly NoteService _thisService;

    /// <summary>
    /// 
    /// </summary>
    /// <param name="noteService"></param>
    public NoteController(NoteService noteService)
    {
        _thisService = noteService;
    }

    /// <summary>
    /// 笔记管理页面
    /// </summary>
    public IActionResult Index(long id)
    {
        ViewData["id"] = id;
        return View();
    }

    /// <summary>
    /// 查询所有/分页
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    [HttpPost("note/pages")]
    public async Task<RestfulResult<PageResult<NtNote>>> GetPagesAsync()
    {
        var restful = new RestfulResult<PageResult<NtNote>>() { Code = CodeStatus.OK };
        using var sr = new StreamReader(Request.Body);
        string dataStr = await sr.ReadToEndAsync();
        if (Request.Body.CanSeek)
            Request.Body.Position = 0;
        if (string.IsNullOrWhiteSpace(dataStr))
            throw new Exception("未提供上传数据。请在Request.Body中携带上传数据。");
        NotePageParam? data = JsonConvert.DeserializeObject<NotePageParam>(dataStr);
        data ??= new NotePageParam { PageNo = 1, PageSize = 10 };
     
        return await _thisService.GetPagesAsync(data);
    }

    /// <summary>
    /// 增加
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    [UnitOfWork]
    [HttpPost("note/add")]
    public async Task<RestfulResult> AddAsync([FromBody] NtNote data)
    {
        return await _thisService.AddAsync(data);
    }

    /// <summary>
    /// 更新
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    [HttpPost("note/update")]
    public async Task<RestfulResult> UpdateAsync([FromBody] NtNote data)
    {
        return await _thisService.UpdateAsync(data);
    }

    /// <summary>
    /// 删除
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    [HttpDelete("note/delete")]
    public async Task<RestfulResult> DeleteAsync([FromBody] EntityBaseIdDto data)
    {
        return await _thisService.DeleteAsync(data);
    }
}